// shopMallPackage/pages/addAddress/addAddress.js
import { createReceiveAddress, updateReceiveAddress, getReceiveAddressDetail } from "../../../service/onetoone_service"
import debounce from "../../../tools/debounce"
import { editAddress, queryAddressDetail } from "../../../service/jb_address_service"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showCityArea: false,
    formData: {
      "district": "",
      "city": "",
      "detailAddress": "",
      "isDefault": false,
      "cityId": null,
      "latitude": "",
      "longitude": "",
      "phone": "",
      "province": "",
      "realName": "",
      id: null,
      detail: "",
      address: null,
    },
    detailId: null, // 已有地址详情id

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        detailId: options.id
      })
      this.getReceiveAddressDetail();
    }
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  getReceiveAddressDetail() {
    wx.showLoading();
    queryAddressDetail(this.data.detailId).then(res => {
      console.log("JJLog:收货地址详情===:" + JSON.stringify(res));
      wx.hideLoading();
      let addressData = res.data;
      if (res.code == 200) {
        let data = {
          "district": addressData.district,
          "city": addressData.city,
          "detailAddress": addressData.detail,
          "isDefault": addressData.isDefault,
          "cityId": addressData.cityId,
          "latitude": "",
          "longitude": "",
          "phone": addressData.phone,
          "province": addressData.province,
          "realName": addressData.realName,
          "detail": addressData.detail,
          id: addressData.id,
          "address": {
            "province": addressData.province,
            "city": addressData.city,
            "district": addressData.district,
            "cityId": 7362
          }
        }
        this.setData({
          formData: data,
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
      console.error("JJLog:queryAddressDetail", err);
    })
  },

  showSelectCityPop() {
    this.setData({
      showCityArea: true,
    })
  },
  // 单行输入回调:
  commonInputBind(e) {
    let key = e.currentTarget.dataset.key;
    let detail = e.detail;
    let changeItem = `formData.${key}`;
    this.setData({
      [changeItem]: detail.value
    })
  },
  //详细地址输入框回调
  bindInputAction(e) {
    this.setData({
      'formData.detail': e.detail.value
    })
  },

  //确定选择区域
  cityPopConfirm(e) {
    let result = e.detail.result;
    // [{ "code": "510000", "name": "四川省" }, { "code": "510400", "name": "攀枝花市" }]
    this.setData({
      'formData.district': result[2].name,
      'formData.city': result[1].name,
      'formData.cityId': result[0].code,
      'formData.province': result[0].name,
      'formData.address': {
        province: result[0].name,
        city: result[1].name,
        district: result[2].name,
        cityId: 7362,
      },
      showCityArea: false,
    })

  },
  cityPopHidden() {
    this.setData({
      showCityArea: false
    })
  },
  //设置默认地址操作：
  settingDefaultAddress() {
    this.setData({
      'formData.isDefault': !this.data.formData.isDefault
    })
  },
  saveAddressAction() {
    if (!this.data.formData.realName.trim()) {
      wx.showToast({
        title: '请填写收货人姓名',
        icon: "none"
      })
      return;
    }
    if (!this.data.formData.phone.trim() | this.data.formData.phone.length != 11) {
      wx.showToast({
        title: '请填写正确的手机号',
        icon: "none"
      })
      return;
    }
    if (!this.data.formData.district) {
      wx.showToast({
        title: '请选择所在省市区',
        icon: "none"
      })
      return;
    }
    if (!this.data.formData.detail) {
      wx.showToast({
        title: '请填写具体地址',
        icon: "none"
      })
      return;
    }
    if (this.data.detailId) {
      //更新:
      debounce(this.updateReceiveAddress);
    } else {
      debounce(this.createReceiveAddress);
    }

  },
  // 保存一个地址
  createReceiveAddress() {
    wx.showLoading();
    editAddress(this.data.formData).then(res => {
      console.log("JJLog:收货地址创建成功===:" + JSON.stringify(res));
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '保存成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 0,
          })
        }, 2000)
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "保存失败",
        icon: "none"
      })
      console.error("JJLog:createReceiveAddress", err);
    })
  },
  updateReceiveAddress() {
    wx.showLoading();
    if (!this.data.formData.cityId) {
      this.setData({
        'formData.cityId': 7362
      })
    }
    editAddress(this.data.formData).then(res => {
      console.log("JJLog:收货地址更新成功===:" + JSON.stringify(res));
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '更新成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 0,
          })
        }, 2000)
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "更新失败",
        icon: "none"
      })
      console.error("JJLog:updateReceiveAddress", err);
    })
  },
})